// com.city.java.announcements.service.impl.AnnouncementServiceImpl.java
package com.city.java.announcements.service.impl;

import com.city.java.announcements.mapper.AnnouncementMapper;
import com.city.java.announcements.pojo.dto.AnnouncementQuery;
import com.city.java.announcements.pojo.entity.Announcements;
import com.city.java.base.response.JsonResult;
import com.city.java.base.response.StatusCode;
import com.city.java.announcements.service.AnnouncementService;
import com.city.java.base.utils.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 公告服务实现类
 */
@Slf4j
@Service
public class AnnouncementServiceImpl implements AnnouncementService {

    @Autowired
    private AnnouncementMapper announcementMapper;

    @Override
    public JsonResult addAnnouncement(Announcements announcement) {
        log.debug("准备添加公告: {}", announcement);

        // 参数校验
        if (announcement == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告信息不能为空");
        }

        if (announcement.getTitle() == null || announcement.getTitle().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告标题不能为空");
        }

        if (announcement.getContent() == null || announcement.getContent().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告内容不能为空");
        }

        // 设置创建时间和更新时间
        if (announcement.getCreatedAt() == null) {
            announcement.setCreatedAt(LocalDateTime.now());
        }
        if (announcement.getUpdatedAt() == null) {
            announcement.setUpdatedAt(LocalDateTime.now());
        }

        // 设置默认状态
        if (announcement.getStatus() == null) {
            announcement.setStatus(Announcements.AnnouncementStatus.draft);
        }

        try {
            announcementMapper.insertAnnouncement(announcement);
            log.info("公告添加成功: 公告ID={}", announcement.getAnnouncementId());
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("添加公告失败: 公告标题={}", announcement.getTitle(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "添加公告失败");
        }
    }

    @Override
    public JsonResult getAnnouncementById(Long announcementId) {
        log.debug("根据ID查询公告: {}", announcementId);

        // 参数校验
        if (announcementId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告ID不能为空");
        }

        try {
            Announcements announcement = announcementMapper.selectById(announcementId);
            if (announcement != null) {
                log.info("查询公告成功: ID={}", announcementId);
                return JsonResult.ok(announcement);
            } else {
                log.warn("公告不存在: ID={}", announcementId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "公告不存在");
            }
        } catch (Exception e) {
            log.error("查询公告失败: ID={}", announcementId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询公告失败");
        }
    }

    @Override
    public JsonResult getAnnouncementsByTypeAndStatus(Announcements.AnnouncementType type, Announcements.AnnouncementStatus status) {
        log.debug("根据类型和状态查询公告列表: type={}, status={}", type, status);

        try {
            List<Announcements> announcements = announcementMapper.selectByTypeAndStatus(type, status);
            log.info("查询类型和状态公告列表成功: 类型={}, 状态={}, 公告数量={}", type, status, announcements.size());
            return JsonResult.ok(announcements);
        } catch (Exception e) {
            log.error("查询类型和状态公告列表失败: 类型={}, 状态={}", type, status, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询公告列表失败");
        }
    }

    @Override
    public JsonResult getAnnouncementsByTitle(String title) {
        log.debug("根据标题查询公告列表: {}", title);

        // 参数校验
        if (title == null || title.trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告标题不能为空");
        }

        try {
            List<Announcements> announcements = announcementMapper.selectByTitle(title);
            log.info("查询标题公告列表成功: 标题={}, 公告数量={}", title, announcements.size());
            return JsonResult.ok(announcements);
        } catch (Exception e) {
            log.error("查询标题公告列表失败: 标题={}", title, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询公告列表失败");
        }
    }

    @Override
    public JsonResult getAllAnnouncements() {
        log.debug("查询所有公告列表");

        try {
            List<Announcements> announcements = announcementMapper.selectAll();
            log.info("查询所有公告列表成功: 公告数量={}", announcements.size());
            return JsonResult.ok(announcements);
        } catch (Exception e) {
            log.error("查询所有公告列表失败", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询公告列表失败");
        }
    }

    @Override
    public PageVO<Announcements> select(AnnouncementQuery query) {
        // 计算分页偏移量
        if (query.getPageNum() != null && query.getPageSize() != null) {
            query.setPageNum((query.getPageNum() - 1) * query.getPageSize());
        }

        List<Announcements> list = announcementMapper.select(query);
        Long total = announcementMapper.getTotalCount(query);

        PageVO<Announcements> pageVO = new PageVO<>();
        pageVO.setList(list);
        pageVO.setTotalPage(total);

        log.debug("查询公告列表成功: {}", list);
        return pageVO;
    }

    @Override
    public JsonResult deleteAnnouncementById(Long announcementId) {
        log.debug("根据ID删除公告: {}", announcementId);

        // 参数校验
        if (announcementId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告ID不能为空");
        }

        try {
            int result = announcementMapper.deleteById(announcementId);
            if (result > 0) {
                log.info("删除公告成功: ID={}", announcementId);
                return JsonResult.ok();
            } else {
                log.warn("删除公告失败，公告不存在: ID={}", announcementId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "公告不存在");
            }
        } catch (Exception e) {
            log.error("删除公告失败: ID={}", announcementId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "删除公告失败");
        }
    }

    @Override
    public JsonResult updateAnnouncement(Announcements announcement) {
        log.debug("更新公告信息: {}", announcement);

        // 参数校验
        if (announcement == null || announcement.getAnnouncementId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告ID不能为空");
        }

        if (announcement.getTitle() != null && announcement.getTitle().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告标题不能为空");
        }

        if (announcement.getContent() != null && announcement.getContent().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "公告内容不能为空");
        }

        try {
            // 检查公告是否存在
            Announcements existingAnnouncement = announcementMapper.selectById(announcement.getAnnouncementId());
            if (existingAnnouncement == null) {
                log.warn("更新公告失败，公告不存在: ID={}", announcement.getAnnouncementId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "公告不存在");
            }

            // 设置更新时间
            announcement.setUpdatedAt(LocalDateTime.now());

            int result = announcementMapper.updateById(announcement);
            if (result > 0) {
                log.info("更新公告成功: ID={}", announcement.getAnnouncementId());
                return JsonResult.ok();
            } else {
                log.warn("更新公告失败: ID={}", announcement.getAnnouncementId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "更新公告失败");
            }
        } catch (Exception e) {
            log.error("更新公告失败: ID={}", announcement.getAnnouncementId(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "更新公告失败");
        }
    }
}
